<template>
    <div style="display: flex">
        <el-button type="primary" style="margin-right: 15px"
            @click="addItem">新增</el-button>
        <el-select style="width: 200px;margin-right: 15px" placeholder="请选择班级" v-model="searchClassId"
                   filterable clearable>
            <el-option v-for="item in classOptions" :key="item.id" :label="item.trainClassNum" :value="item.id">
            </el-option>
        </el-select>
        <el-select style="width: 200px;height: 33px;margin-right: 15px;font-size: 15px;" v-model="courseId"
                   placeholder="请选择课程" filterable clearable>
            <el-option v-for="item in courseOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-button type="primary" style="color: #fff;font-size: 12px;background-color: #1890ff;" @click="load">搜索
        </el-button>
    </div>
    <div>
        <el-table :data="tableData" :row-style="{ height: '77px' }" border
            style="width: calc(100vw - 240px);margin-top: 20px;height: 75vh;color: #909399;font-size: 15px;">
            <el-table-column align="center" prop="trainClassNum" label="班级编号" width="150" />
            <el-table-column align="center" prop="courseName" label="课程名称" width="150" />
            <el-table-column align="center" prop="periodLog" label="班主任日志" width="auto" show-overflow-tooltip="true" />
            <el-table-column align="center" prop="classSum" label="办班总结" width="auto" show-overflow-tooltip="true" />
            <el-table-column align="center" prop="trainSitu" label="执行情况" width="auto" show-overflow-tooltip="true" />
            <el-table-column align="center" prop="createTime" label="创建时间" width="200" />
            <el-table-column align="center" label="操作" fixed="right" width="200">
                <template v-slot="scope">
                    <div>
                        <el-button type="primary" size="small" icon="Edit" @click="editItem(scope.row)">编辑</el-button>
                        <el-button type="danger" size="small" icon="Delete"
                            @click="deleteItem(scope.row.id)">删除</el-button>
                        <br>
                        <el-button type="primary" size="small" icon=document
                            @click="viewAttachment(scope.row)">课堂影像</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <!--      分页-->
        <div style="margin-top: 10px">
            <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper" :total="total" :background="true"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!--添加班级对话框-->
        <el-dialog :close-on-click-modal="false" title="日志操作" v-model="dialogVisible" width="560"
            @close="reset('form')">
            <el-form label-position="left" :inline="true" :model="form" ref="form" :rules="rules">
                <el-form-item label="课程名称" prop="courseId">
                    <el-select v-model="form.courseId" filterable clearable placeholder="请选择课程名称" style="width: 185px">
                        <el-option v-for="item in courseOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <!--<el-form-item label="课堂影像" prop="classPhoto" style="width: 100%">-->
                <!--<el-upload-->
                <!--:on-error="photoHandleError"-->
                <!--:action="'/api/files/upload'"-->
                <!--:on-success="classPhotoUpload"-->
                <!--list-type="picture-card"-->
                <!--:file-list="classPhotoList"-->
                <!--&gt;-->
                <!--<el-icon>-->
                <!--<Plus/>-->
                <!--</el-icon>-->
                <!--<template #file="{ file }" style="display:flex;text-align: center;justify-content: center">-->
                <!--<div>-->
                <!--<img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>-->
                <!--<span class="el-upload-list__item-actions">-->
                <!--<span-->
                <!--class="el-upload-list__item-preview"-->
                <!--@click="handlePictureCardPreview(file.url)"-->
                <!--&gt;-->
                <!--<el-icon><zoom-in/></el-icon>-->
                <!--</span>-->
                <!--<span-->
                <!--class="el-upload-list__item-delete"-->
                <!--@click="handleRemove(file)"-->
                <!--&gt;-->
                <!--<el-icon><Delete/></el-icon>-->
                <!--</span>-->
                <!--</span>-->
                <!--</div>-->
                <!--</template>-->
                <!--</el-upload>-->
                <!--</el-form-item>-->
                <el-form-item label="班主任日志" autocomplete="off" style="width: 100%">
                    <el-input type="textarea" v-model="form.periodLog" :rows="8" placeholder="请输入班主任日志" clearable>
                    </el-input>
                </el-form-item>
                <el-form-item label="办班总结" autocomplete="off" style="width: 100%">
                    <el-input type="textarea" v-model="form.classSum" :rows="8" placeholder="请输入办班总结" clearable>
                    </el-input>
                </el-form-item>
                <el-form-item label="执行情况" autocomplete="off" style="width: 100%">
                    <el-input type="textarea" v-model="form.trainSitu" :rows="8" placeholder="请输入执行情况" clearable>
                    </el-input>
                </el-form-item>
                <el-form-item label="课堂影像" autocomplete="off" style="width: 100%">
                    <el-upload :action="'api/files/upload'" :file-list="fileList" :before-upload="beforeUpload"
                        :on-success="attachmentUploadSuccess" :on-remove="attachmentRemove" style="width:100%" drag
                        multiple>
                        <el-icon class="el-icon--upload">
                            <upload-filled />
                        </el-icon>
                        <div class="el-upload__text">
                            拖拽或<em>点击</em>上传
                        </div>
                        <div class="el-upload__tip">
                            (请上传小于1GB的文件)
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="reset('form')">取消</el-button>
                    <el-button type="primary" @click="submitForm('form')">保存</el-button>
                </div>
            </template>
        </el-dialog>
        <div v-if="dialogImageVisible" class="modal" @click="closeModal">
            <div class="modal-content" @click.stop>
                <!-- Close button -->
                <button class="close-btn" @click="closeModal">X</button>
                <img :src="dialogImageUrl" alt="" class="enlarged-image"
                    :style="{ transform: 'scale(' + zoomLevel + ')' }" @wheel="handleZoom">
            </div>
        </div>

        <el-dialog v-model="attachmentVisible" :close-on-click-modal="false" title="相关附件" width="1000px" align-center
            draggable>
            <div class="attachmentDialog">
                <div class="attachmentTitle">
                    <span>课堂影像</span>
                </div>
                <el-table :data="attachmentTable" :cell-style="cellStyle" highlight-current-row
                    :header-cell-style="{ background: '#f4f3f9' }" class="attachmentTable"
                    style="width:100%;height:calc(100% - 29px)" border>
                    <el-table-column align="center" prop="fileName" label="课堂影像">
                    </el-table-column>
                    <el-table-column align="center" label="查看">
                        <template v-slot="scope">
                            <el-button type="primary" icon="view" size="small"
                                @click="viewFile(scope.row)">查看</el-button>
                            <el-button type="primary" icon="Download" size="small"
                                @click="downloadFile(scope.row)">下载</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-dialog>

        <el-dialog title="文件预览" v-model="openItemFileDialog" width="70%" top="5vh" class="custom-preview-dialog"
            @close="closeFile">
            <div class="preview-container" v-if="openItemFileDialog">
                <!-- PDF 预览 -->
                <vue-office-pdf v-if="fileExt === 'docx' || fileExt === 'doc'" :src="pdfSrc" style="height: 600px" />

                <iframe v-if="fileExt !== 'docx' && fileExt !== 'doc'" :src="pdfSrc" frameborder="0"
                    style="background-color: #fff;width: 100%; height: 600px"></iframe>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { ref } from 'vue'
import request from "~/utils/request.js";
import { ElMessage } from "element-plus";
import VueOfficePdf from '@vue-office/pdf'

export default {
    components: {
        VueOfficePdf
    },
    data() {
        return {
            dialogVisible: false,
            tableData: [],
            form: {},
            courseOptions: [],
            classOptions: [],
            courseId: '',
            searchClassId: '',
            classPhotoList: [],
            currentPage: 1,
            pageSize: 10,
            total: 0,
            rules: [],
            dialogImageUrl: '',
            dialogImageVisible: false,
            attachmentVisible: false, // 相关附件弹窗
            openItemFileDialog: false, // 文件预览弹窗
            attachmentTable: [],
            fileList: [], // 专门用于el-upload的文件列表
        }
    },
    async created() {
        await this.getClassOptions()
        await this.load()
        this.getCourseOptions()
    },
    methods: {
        async getClassOptions() {
            request.get("/train-class/all").then(res => {
                this.classOptions = res.data
            })
        },
        async load() {
            console.log(this.searchClassId)
            if (this.$route.query.classId === undefined && this.searchClassId === undefined) {
                this.searchClassId = ''
            } else if (this.$route.query.classId !== undefined) {
                this.searchClassId = Number(this.$route.query.classId)
            }
            if (this.courseId === undefined) {
                this.courseId = ''
            }
            request.get("/stu-certificate/page?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize + "&courseId=" + this.courseId + "&classId=" + this.searchClassId).then(res => {
                if (res.code === '200') {
                    for (let key in res.data) {
                        if (key === "records") {
                            this.tableData = res.data[key];
                        } else if (key === "total") {
                            this.total = res.data[key];
                        }
                    }
                } else {
                    ElMessage.error("错误" + res.msg)
                }
            })
        },
        getCourseOptions() {
            if (this.$route.query.classId === undefined) {
                this.classId = ''
            } else {
                this.classId = this.$route.query.classId
            }
            request.get("/course/getCourseByClassId?classId=" + this.classId).then(res => {
                this.courseOptions = res.data
            })
        },
        // editItem(item) {
        //     Object.assign(this.form, item)
        //     this.dialogVisible = true
        //     this.initclassPhotoList()
        // },
        addItem() {
            this.dialogVisible = true;
        },
        // 删除
        deleteItem(scope) {
            this.$confirm('是否确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                request.get("/stu-certificate/delete/" + scope).then(res => {
                    if (res.code === '200') {
                        this.$message.success("成功")
                        this.load()
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            });
        },
        editItem(item) {
            request.get("attachment/getAttachment", {
                params: {
                    correlationTable: "stu_certificate",
                    correlationId: item.id
                }
            }).then(res => {
                if (res.code === '200') {
                    this.form = {
                        ...item,
                        attachment: res.data.records,
                    };
                    // 转换附件数据为el-upload需要的格式
                    this.fileList = res.data.records.map(file => ({
                        id: file.id,
                        name: file.fileName,
                        url: file.filePath,
                    }));
                    this.dialogVisible = true
                }
            })
        },
        // 提交
        submitForm(val) {
            if (this.form.classId !== null && this.form.classId !== undefined) {

            } else if (this.$route.query.classId === undefined) {
                this.form.classId = ''
            } else {
                this.form.classId = this.$route.query.classId
            }
            this.$refs[val].validate((valid) => {
                if (valid) {
                    request.post("/stu-certificate/edit", this.form).then(res => {
                        if (res.code === '200') {
                            this.$message({
                                message: "成功",
                                type: "success"
                            })
                            this.load()
                            this.reset(val)
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                }
            })
        },
        // 取消
        reset(val) {
            this.dialogVisible = false;
            this.form = {};
            this.classPhotoList = [];
            this.$refs[val].resetFields();
        },
        handleCurrentChange(item) {
            // 改变当前页码触发
            this.currentPage = item
            this.load()
        },
        handleSizeChange(item) {   // 改变当前每页的个数触发
            this.pageSize = item
            this.load()
        },
        photoHandleSuccess(response) {
            this.form.url = `/api/file/download/${response}`
            this.$message.success('上传成功');
        },
        photoHandleError() {
            this.$message.error("上传文件失败")
        },
        deleteImage() {
            this.form.url = '';
            this.$message.success('删除成功');
        },
        handlePictureCardPreview(url) {
            this.dialogImageUrl = url;
            this.dialogImageVisible = true;
        },
        handleRemove(file) {
            const index = this.classPhotoList.indexOf(file);
            if (index !== -1) {
                const images = this.form.classPhoto.split(',');
                images.splice(index, 1); // 删除选中的图片
                this.form.classPhoto = images.join(','); // 更新 pointMap 字符串
                this.classPhotoList.splice(index, 1);
            }
        },
        handleZoom(event) {
            event.preventDefault(); // 防止页面滚动

            // 根据滚轮方向调整缩放级别
            if (event.deltaY < 0) {
                this.zoomLevel = Math.min(this.zoomLevel + 0.1, 3); // 最大缩放到3倍
            } else {
                this.zoomLevel = Math.max(this.zoomLevel - 0.1, 1); // 最小缩放到1倍
            }
        },
        closeModal() {
            this.dialogImageUrl = ''
            this.dialogImageVisible = false
            this.zoomLevel = 1; // 重置缩放级别
        },
        classPhotoUpload(response) {
            // this.pointMapList = this.form.pointMap.split(',');

            if (this.classPhotoList.length === 0) {
                this.form.classPhoto = `/api/file/download/${response}`
            } else {
                this.form.classPhoto = this.form.classPhoto + `,/api/file/download/${response}`
            }
            this.initclassPhotoList()
            console.log(this.classPhotoList)
            console.log(this.form.classPhoto)
        },
        initclassPhotoList() {
            this.classPhotoList = this.form.classPhoto ? this.form.classPhoto.split(',').map(url => {
                return { url }
            }) : [];
            console.log(this.classPhotoList)
        },

        // 上传前的文件验证
        beforeUpload(file) {
            const maxSize = 1024 * 1024 * 1024;
            if (file.size > maxSize) {
                this.$message.warning('文件大小超过1GB限制!');
                return false;
            }
            return true;
        },
        // 上传文件成功
        attachmentUploadSuccess(response, file, fileList) {
            this.form.attachment.push({
                id: null,
                uid: file.uid,
                fileName: file.name,
                filePath: `/api/file/download/${response}`
            });
            this.$message.success('上传成功');
        }
        ,
        attachmentRemove(file, fileList) {
            if (!file.id) {
                // 移除对应的文件
                this.form.attachment = this.form.attachment.filter(f => f.uid !== file.uid);
                return;
            }
            request.get(`/attachment/delete/${file.id}`).then(res => {
                if (res.code != '200') {
                    return;
                }
                if (res.data.toString() == "true") {
                    this.form.attachment = this.form.attachment.filter((f) => f.id !== file.id);
                    this.$message.success('删除成功');
                } else {
                    this.$message.error('删除失败');
                }
            })
        },

        // 查看附件
        viewAttachment(row) {
            // 查看附件
            request.get("attachment/getAttachment", {
                params: {
                    correlationTable: "stu_certificate",
                    correlationId: row.id
                }
            }).then(res => {
                if (res.code === '200') {
                    this.attachmentTable = res.data.records
                }
            })
            this.attachmentVisible = true
        },
        // 关闭相关附件弹窗
        closeAttachmentDialog() {
            this.attachmentVisible = false
        },
        // 下载文件
        downloadFile(item) {
            const link = document.createElement('a');
            link.href = item.filePath;
            link.download = item.fileName || '未知文件';

            // 兼容某些浏览器
            document.body.appendChild(link);

            link.click();
            setTimeout(() => {
                document.body.removeChild(link);
            }, 0);
        },
        // 查看文件
        async viewFile(item) {
            const { filePath, fileName } = item;

            this.fileExt = fileName.split('.').pop().toLowerCase()

            try {
                if (this.fileExt !== "docx" && this.fileExt !== "doc") {
                    this.pdfSrc = filePath
                } else {
                    const previewUrl = `/api/files/preview/${encodeURIComponent(filePath.split('/').pop())}`
                    const response = await fetch(previewUrl)
                    const blob = await response.blob()

                    this.pdfSrc = URL.createObjectURL(blob)
                }
                this.openItemFileDialog = true
            } catch (error) {
                this.$message.error('文档预览失败: ' + error.message)
            }
        },
        closeFile() {
            this.openItemFileDialog = false
            // 释放URL对象
            if (this.pdfSrc && this.pdfSrc.startsWith('blob:')) {
                URL.revokeObjectURL(this.pdfSrc);
            }
            this.pdfSrc = "";

            // 销毁iframe的资源
            const iframes = document.querySelectorAll('iframe');
            iframes.forEach(iframe => {
                iframe.src = 'about:blank';
            });
        },
        handleClear() {
            this.searchClassId = ''
            this.$route.query.classId = ''
        },
    }
}
</script>

<style scoped>
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    /* 使用视口宽度 */
    height: 100vh;
    /* 使用视口高度 */
    background-color: rgba(0, 0, 0, 0.9);
    /* 更深的半透明背景 */
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9000;
    /* 确保弹窗在最上层 */
}

.modal-content {
    position: relative;
    /* 相对定位，用于定位关闭按钮 */
    width: 100%;
    /* 弹窗内容宽度为100% */
    height: 100%;
    /* 弹窗内容高度为100% */
    display: flex;
    justify-content: center;
    align-items: center;
}

.close-btn {
    z-index: 9999;
    position: absolute;
    top: 20px;
    /* 离顶部距离 */
    right: 20px;
    /* 离右侧距离 */
    background-color: transparent;
    /* 背景透明 */
    border: none;
    font-size: 24px;
    /* 字体大小 */
    cursor: pointer;
    color: red;
    /* 关闭按钮颜色 */
}

.close-btn:hover {
    color: red;
    /* 鼠标悬停时颜色变化 */
}

.enlarged-image {
    max-width: 100%;
    /* 确保图片不会超出弹窗边界 */
    max-height: 100%;
    /* 确保图片不会超出弹窗边界 */
    border-radius: 0;
    /* 去掉图片的圆角 */
    transition: transform 0.3s ease;
    /* 变换过渡效果 */
}

::v-deep .custom-preview-dialog {
    /* 限制弹窗最大高度为视口的90% */
    max-height: 90vh;
    display: flex;
    flex-direction: column;
}

/* 内容容器 */
::v-deep .custom-preview-dialog .el-dialog__body {
    flex: 1;
    padding: 0 !important;
    /* 移除默认padding */
    overflow: hidden;
    /* 隐藏溢出内容 */
}

.preview-container {
    height: 100%;
    display: flex;
    flex-direction: column;
}

/* Office内容区域 */
.office-content {
    flex: 1;
    /* 填充剩余空间 */
    min-height: 400px;
    /* 最小高度保证 */
    overflow: auto;
    /* 添加滚动条 */
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    background: white;
}

.office-content {
    word-wrap: break-word;
    overflow-wrap: break-word;
}

/* 调整TXT预览样式 */
pre {
    flex: 1;
    overflow: auto;
    margin: 0;
    background: white;
    padding: 20px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
}

.enlarged-image {
    max-width: 100%;
    /* 确保图片不会超出弹窗边界 */
    max-height: 100%;
    /* 确保图片不会超出弹窗边界 */
    border-radius: 0;
    /* 去掉图片的圆角 */
    transition: transform 0.3s ease;
    /* 变换过渡效果 */
}
</style>
